﻿using System;
//using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
//using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Net;
using System.Threading;

/* if want to use background worker, need to reference BackgroundWorker.dll*/

namespace Wince6_app2 {
	public partial class form_iTeach : Form {

		private bool _docLoaded = false;

		public form_iTeach() {
			InitializeComponent();
			this.timer1.Enabled = true;
			this.timer1.Interval = 2000;
		}


		private void form_iTeach_Load( object sender, EventArgs e ) {

			this.webBrowser1.Visible = false;
			this.webBrowser1.Hide();

			this.label1.Dock = DockStyle.Fill;			
		}		


		/// <summary>
		/// Loads website after initial time interval
		/// to ensure that Internet is already available.
		/// </summary>
		private void timer1_Tick( object sender, EventArgs e ) {

			// Disable initial timer
			this.timer1.Enabled = false;

			WaitForInternetReady();

			// hide message label
			//
			this.label1.Text = "Connected successfully !!";
			this.label1.Visible = false;
			this.label1.Enabled = false;

			// now go to page
			//
			this.webBrowser1.Visible = true;
			this.webBrowser1.Show();
			this.webBrowser1.Dock = DockStyle.Fill;

			Uri page = new Uri( @"http://www.iteachs.com/server" );
			//this.webBrowser1.Url = page;
			this.webBrowser1.Navigate( page );
			//this.webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler( webBrowser1_DocumentCompleted );
			//this.webBrowser1.Navigating += new WebBrowserNavigatingEventHandler( webBrowser1_Navigating );						
		}

		/// <summary>
		/// Sets timeout before browser navigates so that
		/// if internet is not available, browser auto refreshes.
		/// </summary>		
		//void webBrowser1_Navigating( object sender, WebBrowserNavigatingEventArgs e ) {
		//    this.timer2.Enabled = true;
		//    this.timer2.Interval = 15000;

		//    this._docLoaded = false;
		//}

		/// <summary>
		/// Disables timer2.
		/// </summary>		
		//void webBrowser1_DocumentCompleted( object sender, WebBrowserDocumentCompletedEventArgs e ) {
			
		//    _docLoaded = true;

		//    this.timer2.Enabled = false;
		//}

		/// <summary>
		/// If website is offline at every tick, refresh it.
		/// </summary>		
		private void timer2_Tick( object sender, EventArgs e ) {
			if ( !this.webBrowser1.IsBusy && !this._docLoaded ) {
				this.webBrowser1.Refresh();
			}
		}


		//private void StartThreads() {
		//    List<Thread> threads = new List<Thread>();

		//    Thread bgThread1 = new Thread( new ThreadStart( DoNothing ) );
		//    threads.Add( bgThread1 );
		//    bgThread1.Start();

		//    Thread bgThread2 = new Thread( new ThreadStart( WaitForInternetReady ) );
		//    threads.Add( bgThread2 );
		//    bgThread2.Start();

		//    foreach ( Thread thread in threads ) {
		//        thread.Join();
		//    }
		//}

		//private void DoNothing() {

		//}


		/// <summary>
		/// Sleeps until connected to internet.
		/// </summary>
		private void WaitForInternetReady() {
			string url = @"http://www.iteachs.com/server";
			
			bool connected = false;

			while ( !connected ) {
				HttpWebRequest request;
				HttpWebResponse response;
				try {
					request = (HttpWebRequest)WebRequest.Create( url );
					request.Timeout = 2000;
					request.Credentials = CredentialCache.DefaultCredentials;

					response = (HttpWebResponse)request.GetResponse();
					if ( response.StatusCode == HttpStatusCode.OK ) {
						connected = true;
						if ( response != null )
							response.Close();
					}
				}
				catch ( WebException ex ) {					
				}
				//finally {
				//    if ( response != null )
				//        response.Close();
				//}
				System.Threading.Thread.Sleep( 1000 );
			}

			//int forceConnectionFlag = 1;
			//while ( !InternetCheckConnection( url, forceConnectionFlag, 0 ) ) {
			//    System.Threading.Thread.Sleep( 1000 );
			//}
		}

		//// Declare the worker
		//private BackgroundWorker _worker;

		//private void InitBW() {
		//    _worker = new BackgroundWorker( this );
		//    _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler( mBW_RunWorkerCompleted );
		//    _worker.DoWork += new DoWorkEventHandler( mBW_DoWork );
		//}

		//void mBW_RunWorkerCompleted( object sender, RunWorkerCompletedEventArgs e ) {
		//    // hide message label
		//    this.label1.Text = "Connected successfully !!";
		//    //this.label1.Visible = false;
		//    //this.label1.Enabled = false;

		//    // now go to page
		//    //
		//    //this.webBrowser1.Visible = true;
		//    //this.webBrowser1.Show();
		//    //this.webBrowser1.Dock = DockStyle.Fill;

		//    Uri page = new Uri( @"http://www.iteachs.com/server" );
		//    //this.webBrowser1.Url = page;
		//    //this.webBrowser1.Navigate( page );
		//}

		//void mBW_DoWork( object sender, DoWorkEventArgs e ) {
		//    // Sleeps until connected to internet
		//    //
		//    WaitForInternetReady();
		//}
		

		//private void WaitForInternetReady() {
		//    string url = @"http://www.iteachs.com/server";

		//    int forceConnectionFlag = 1;
		//    //while ( !InternetCheckConnection( url, forceConnectionFlag, 0 ) ) {
		//        //System.Threading.Thread.Sleep( 1000 );
		//        for ( int i = 0; i < 1000; i++ ) {
		//        }
		//    //}
		//}

		//http://msdn.microsoft.com/en-us/library/aa384702%28VS.85%29.aspx
		[DllImport( "wininet.dll", CharSet = CharSet.Auto )]
		private extern static bool InternetGetConnectedState( ref InternetConnectionState_enum lpdwFlags, int dwReserved );

		//http://msdn.microsoft.com/en-us/library/aa384346%28VS.85%29.aspx
		[DllImport( "wininet.dll", CharSet = CharSet.Auto )]
		private extern static bool InternetCheckConnection( string lpszUrl, int dwFlags, int dwReserved );


		[Flags]
		enum InternetConnectionState_enum : int {
			INTERNET_CONNECTION_MODEM = 0x1,
			INTERNET_CONNECTION_LAN = 0x2,
			INTERNET_CONNECTION_PROXY = 0x4,
			INTERNET_RAS_INSTALLED = 0x10,
			INTERNET_CONNECTION_OFFLINE = 0x20,
			INTERNET_CONNECTION_CONFIGURED = 0x40
		}

		static bool IsConnectedToNetwork() {
			InternetConnectionState_enum _flag = 0;
			return InternetGetConnectedState( ref _flag, 0 );
			//return InternetCheckConnection(
		}	
			
	}
}